package org.tyut.xyl.game;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.liugang.tugofwar.R;
import com.google.gson.Gson;

import org.tyut.xyl.game.util.GsonUtil;
import org.tyut.xyl.game.util.Information;
import org.tyut.xyl.game.util.OkHttpUtil;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;


public class SigninActivity extends AppCompatActivity {

    private TextView signin_tip;

    public void onClick(View view) {
        EditText username_et = (EditText) findViewById(R.id.signin_username);
        EditText passwd_et = (EditText) findViewById(R.id.signin_passwd);
        String username = username_et.getText().toString();
        String password = passwd_et.getText().toString();
        FormBody formBody = new FormBody.Builder()
                .add("username", username)
                .add("password", password)
                .build();
        Request request = new Request.Builder().url(Information.URL + "signin")
                .post(formBody).build();
        Call call = OkHttpUtil.getOkHttpClient().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseJson = Objects.requireNonNull(response.body()).string();
                Gson gson = GsonUtil.getGsonBuilder().create();
                Map<String, String> ansMap = gson.fromJson(responseJson, Map.class);

                MainActivity.userid = ansMap.get("userid");
                MainActivity.username = (String) ansMap.get("username");
                Intent intent = new Intent(SigninActivity.this, GameMainActivity.class);
                startActivity(intent);
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

                signin_tip.setText("注册失败");
            }
        });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signin);
        signin_tip = (TextView) findViewById(R.id.signin_tip);

    }

}
